<template>
	<view class="page-container bg-grey">
		<up-navbar safeAreaInsetTop fixed placeholder title="订单支付" @leftClick="pageBack"></up-navbar>
		<view class="plr-24 text-center">
			<view class="mt-96 font-bold">
				<text class="fs-40 mr-12">&yen;</text>
				<text class="fs-80">{{ priceInCent(orderDetail.amount_in_cent) }}</text>
			</view>
			<view class="mt-12 c-grey-86 fs-24" v-if="showCountDown">支付剩余时间 {{ countDownStr }}</view>
			<view class="mt-96">
				<view
					v-for="(paymentItem, index) in paymentList"
					:key="index"
					class="payment-item"
					@click="changePaymentItem(paymentItem)"
				>
					<view class="flex-a">
						<image :src="paymentItem.img_url" class="icon-56" />
						<text class="fs-32 c-black-_9 ml-16">{{ paymentItem.name }}</text>
					</view>
					<image
						v-if="selectPaymentItem.id == paymentItem.id"
						:src="imgBaseUrl + 'icon-checked.png'"
						class="icon-40"
					/>
					<image v-else :src="imgBaseUrl + 'icon-uncheck.png'" class="icon-40" />
				</view>
			</view>
		</view>
		<view class="bottom-fixed-wrap flex-a">
			<view class="flex-1">
				<zjy-button @click="submitPay" :disabled="payState">立即支付</zjy-button>
			</view>
		</view>
	</view>
</template>
<script setup lang="ts">
import { ref, inject } from "vue"
import { onLoad } from "@dcloudio/uni-app"
import { priceInCent } from "@/mixins/mixins"
import { addZero } from "@/utils/tools"
import { $getPaymentList, $getStmtDetail, $shopOfflinePay } from "@/api/order"
import { pageBack } from "@/utils/page-redirect"

const imgBaseUrl = inject("imgBaseUrl")
const orderDetail = ref<any>({})
const paymentList = ref<any[]>([])
const selectPaymentItem = ref<any>()
let stmtId = ""

const changePaymentItem = (paymentItem: any) => {
	selectPaymentItem.value = paymentItem
}
const getOrderDetail = () => {
	$getStmtDetail(stmtId).then((data: any) => {
		orderDetail.value = data
		if (data.state == 10) {
			countDownPay(data.deadline)
		}
	})
}
const getPaymentList = () => {
	$getPaymentList().then((data: any) => {
		if (!data || data.list <= 0) {
			return
		}
		paymentList.value = data.list
		selectPaymentItem.value = data?.list[0]
	})
}
//#region 支付倒计时
const showCountDown = ref(false)
const countDownStr = ref("00:00")
const countDownTimer = ref()
const countDownPay = (deadlineDate: string) => {
	var deadLineTime = Date.parse(deadlineDate)
	if (deadLineTime > new Date().getTime()) {
		countDownTimer.value = null
		countDown(deadLineTime)
		showCountDown.value = true
	}
}
const countDown = (deadLineTime: number) => {
	var leftSeconds = (deadLineTime - new Date().getTime()) / 1000
	if (leftSeconds <= 0) {
		clearTimeout(countDownTimer.value)
	} else {
		var m = Math.floor((leftSeconds / 60) % 60),
			s = Math.floor(leftSeconds % 60)
		countDownStr.value = addZero(m < 0 ? 0 : m) + ":" + addZero(s < 0 ? 0 : s)
		countDownTimer.value = setTimeout(() => {
			countDown(deadLineTime)
		}, 1000)
	}
}
//#endregion
//#region 支付
const payState = ref(false)
let weixinPayState = 0
let rePlayLoader: any = null
let startPayLoader: any = null
const submitPay = () => {
	const that = this
	if (payState.value) {
		return false
	}
	payState.value = true
	uni.showLoading({
		title: "加载中...",
	})
	setTimeout(() => {
		uni.hideLoading()
	}, 2000)

	clearPageTimeout()
	rePlayLoader = setTimeout(() => {
		uni.showModal({
			title: "提示",
			content: "请您确认完成“微信支付”",
			cancelText: "重试",
			cancelColor: "#FEE038",
			confirmText: "完成支付",
			confirmColor: "#444444",
			success: function (res) {
				if (res.confirm) {
					if (weixinPayState == 1) {
						toOrderDetail()
					} else {
						uni.showModal({
							title: "提示",
							content: "很抱歉，支付未完成！",
							showCancel: false,
						})
						payState.value = false
						uni.hideLoading()
					}
				} else if (res.cancel) {
					startWeixinPay()
				}
			},
		})
	}, 8000)

	startWeixinPay()
}
const startWeixinPay = () => {
	startPayLoader = null
	const postData = {
		stmtId,
		// paymentConfigurationId: selectPaymentItem.value.id,
	}

	// TODO: 现金付
	// if (selectPaymentItem.value.payment_method.payment_scenario == 10) {
	if (1 == 1) {
		//现金付
		startPayLoader = $shopOfflinePay(postData)
			.then(() => {
				toOrderDetail()
			})
			.catch((err: any) => {
				uni.showModal({
					title: "提示",
					content: err.message,
					showCancel: false,
				})
				payState.value = false
			})
	} else {
		startPayLoader = $shopJournalsOnlinePay(stmtId, postData)
			.then((data: any) => {
				uni.requestPayment({
					provider: "wxpay",
					orderInfo: {},
					timeStamp: data.timestamp,
					nonceStr: data.nonce_str,
					package: data.package_str,
					signType: data.sign_type,
					paySign: data.pay_sign,
					success: function () {
						weixinPayState = 1
					},
					fail: function () {
						startPayLoader = null
						payState.value = false
					},
				})
			})
			.catch((err: any) => {
				uni.showModal({
					title: "提示",
					content: err.message,
					showCancel: false,
				})
				payState.value = false
			})
	}
}
const toOrderDetail = () => {
	clearPageTimeout()
	setTimeout(() => {
		uni.switchTab({ url: "/pages/home/order" })
	}, 2000)
}
const clearPageTimeout = () => {
	rePlayLoader && clearTimeout(rePlayLoader)
}
//#endregion
onLoad((options) => {
	stmtId = options?.stmt_id
	getOrderDetail()
	// getPaymentList()
})
onBeforeUnmount(() => {
	clearPageTimeout()
})
</script>
<style lang="scss" scoped>
.payment-item {
	padding: 40rpx 32rpx;
	margin-bottom: 24rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	background: $c-white;
	border-radius: 16rpx;
}
</style>
